﻿using Bzstd.Entity;
using Bzstd.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Bzstd.Controllers;

public class SteamActionFilter(ILogger<SteamActionFilter> logger) : ActionFilterAttribute
{
	public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
	{
		if (actionExecutedContext.Exception != null)
		{
			logger.LogException(actionExecutedContext.Exception);
			var exception = actionExecutedContext.Exception.GetRootException();
			actionExecutedContext.ExceptionHandled = true;
			actionExecutedContext.Result = new BadRequestObjectResult(new
			{
				message = exception.Message,
				error = exception.GetType().FullName,
				stackStace = exception.StackTrace
			});
		}
		else
		{
			switch (actionExecutedContext.Result)
			{
				case EmptyResult:
				{
					actionExecutedContext.Result = new OkObjectResult(new { message = "操作成功" });
					return;
				}
				case ObjectResult objectResult:
				{
					if (objectResult.Value is JsonWrapper w)
					{
						actionExecutedContext.Result = new OkObjectResult(new
						{
							data = w.Data,
							message = w.Message
						}) { StatusCode = w.Result ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest };
					}
					else
					{
						actionExecutedContext.Result = new OkObjectResult(new
						{
							data = objectResult.Value,
							message = "查询成功"
						});
					}
					return;
				}
			}
		}
	}
}
